<template>
  <span v-if="isShow === false">正在登录...</span>
  <div class="common-bg" v-else>
    <div class="wrap">
      <div class="form">
        <h2>QQ登录</h2>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="绑定已有账号" name="first">
            <el-form
                ref="loginForm"
                :model="login.form"
                :rules="login.rules"
                label-width="80px"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="login.form.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="login.form.password"></el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="submitLoginForm('loginForm')"
                >登录并绑定</el-button
                >
                <el-button type="warning" @click="resetForm('loginForm')">Reset</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="注册新账号并绑定" name="second">
            <el-form
                ref="registerForm"
                :model="register.form"
                :rules="register.rules"
                label-width="80px"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="register.form.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="register.form.password"></el-input>
              </el-form-item>
              <el-form-item label="氏族" prop="team">
                <el-select v-model="register.form.team" placeholder="氏族">
                  <el-option label="一团" value="一团"></el-option>
                  <el-option label="二团" value="二团"></el-option>
                  <el-option label="三团" value="三团"></el-option>
                  <el-option label="四团" value="四团"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="游戏ID" prop="nickname">
                <el-input  v-model="register.form.nickname"></el-input>
              </el-form-item>
              <el-form-item label="QQ" prop="qq">
                <el-input v-model="register.form.qq"></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="sex">
                <el-radio-group v-model="register.form.sex">
                  <el-radio label="男" value="男"></el-radio>
                  <el-radio label="女" value="女"></el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="submitRegisterForm('registerForm')"
                >注册并绑定</el-button
                >
                <el-button type="warning" @click="resetForm('registerForm')">Reset</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script>

import {ref} from "vue";
import {QQBindLogin, QQBindRegister, QQLogin} from "../../api/common";
import {ElLoading} from "element-plus";
import {error, success} from "../../utils/message";

export default {
  name: "QqLogin",
  data(){
    return {
      isShow: false,
      open_id: '',
      access_token: '',
      activeName:'first',
      register:{
        form:{
          username:'',
          password:'',
          nickname:'',
          team:'',
          qq:'',
          sex:ref('男')
        },
        rules:{
          username: [{
            required:true,
            message:"请输入用户名",
            trigger:'blur'
          },{
            min:3,
            max:15,
            message: "请输入3~15个字符",
            trigger: 'blur'
          }],
          password: [{
            required:true,
            message:"请输入密码",
            trigger:'blur'
          },{
            min:3,
            max:15,
            message: "请输入3~15个字符",
            trigger: 'blur'
          }],
          team:[{
            required:true,
            message:"请选择所在氏族",
            trigger:'change'
          }],
          nickname: [{
            required:true,
            message:"请输入游戏ID",
            trigger:'blur'
          },{
            min:3,
            max:25,
            message: "请输入3~25个字符",
            trigger: 'blur'
          }],
          qq:[{
            required:true,
            message:"请输入您的QQ",
            trigger:'blur'
          },{
            min:5,
            max:15,
            message: "请输入正确的QQ号码",
            trigger: 'blur'
          }],
          sex:[{
            required:true,
            message:"请选择您的性别",
            trigger:'change'
          }]
        }
      },
      login:{
        form:{},
        rules:{
          username: [{
            required:true,
            message:"请输入用户名",
            trigger:'blur'
          },{
            min:3,
            max:15,
            message: "请输入3~15个字符",
            trigger: 'blur'
          }],
          password: [{
            required:true,
            message:"请输入密码",
            trigger:'blur'
          },{
            min:3,
            max:15,
            message: "请输入3~15个字符",
            trigger: 'blur'
          }],
        }
      }
    }
  },
  methods:{
    getInfo: function (){
      if (QC.Login.check()){
        const vm = this;
        console.log('已经登录')
        QC.Login.getMe(function (openId, accessToken) {
          vm.open_id = openId
          vm.access_token = accessToken
          vm.doLogin()
        })
      }else {
        console.log("登录失败");
      }
    },
    doLogin: async function(){
      const vm = this;
      let params = {
        access: vm.open_id
      }
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      const { code, data, message } = await QQLogin(params)
      if (+code === 200) {
        success(message)
        const targetPath = decodeURIComponent(this.$route.query.redirect)
        if (targetPath.startsWith('http')) {
          // 如果是一个url地址
          window.location.href = targetPath
        } else if (targetPath.startsWith('/')) {
          // 如果是内部路由地址
          this.$router.push(targetPath)
        } else {
          this.$router.push('/')
        }
        this.$store.commit('app/setToken', data)
      } else {
        error(message)
        vm.isShow = true
      }
      loading.close()
    },
    resetForm: function (formName) {
      this.$refs[formName].resetFields()
    },
    submitLoginForm:function (formName){
      let vm = this;
      this.$refs[formName].validate((valid)=>{
        if (valid) {
          vm.doBindQQ();
        } else {
          error('请检查表单项')
          return false
        }
      })
    },
    submitRegisterForm:function (formName){
      let vm = this;
      this.$refs[formName].validate((valid)=>{
        if (valid) {
          vm.doRegister();
        } else {
          error('请检查表单项')
          return false
        }
      })
    },
    doRegister:async function (){
      let vm = this;
      vm.register.form.access = vm.open_id
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      const { code, data, message } = await QQBindRegister(vm.register.form)
      if (+code === 200) {
        success(message)
        const targetPath = decodeURIComponent(this.$route.query.redirect)
        if (targetPath.startsWith('http')) {
          // 如果是一个url地址
          window.location.href = targetPath
        } else if (targetPath.startsWith('/')) {
          // 如果是内部路由地址
          this.$router.push(targetPath)
        } else {
          this.$router.push('/')
        }
        this.$store.commit('app/setToken', data)
      } else {
        error(message)
        vm.isShow = true
      }
      loading.close()

    },
    doBindQQ:async function (){
      let vm = this;
      vm.login.form.access = vm.open_id
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
      const { code, data, message } = await QQBindLogin(vm.login.form)
      if (+code === 200) {
        success(message)
        const targetPath = decodeURIComponent(this.$route.query.redirect)
        if (targetPath.startsWith('http')) {
          // 如果是一个url地址
          window.location.href = targetPath
        } else if (targetPath.startsWith('/')) {
          // 如果是内部路由地址
          this.$router.push(targetPath)
        } else {
          this.$router.push('/')
        }
        this.$store.commit('app/setToken', data)
      } else {
        error(message)
        vm.isShow = true
      }
      loading.close()
    }
  },
  mounted() {
    this.$nextTick(function (){
      this.getInfo()
    })
  }
}
</script>

<style scoped>
.wrap {
  width: 45%;
  height: auto;
  min-width: 360px;
  position: absolute;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  background: rgba(255,255,255,.7);
  border-radius: 5px;
}
.form {
  padding:100px 40px;
}
.form h2{
  display: block;
  text-align: center;
  margin: 40px;

}
.opt{
  padding: 35px 0;
}
</style>